/*
 * Copyright 2012-2014 the original author or authors.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.jqd.framework.core.spring.context;

import java.io.IOException;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.jqd.framework.util.PropertiesUtils;

/**
 * 
 * 获取当前应用中spring容器
 * 
 * @author liaozhicheng.cn@gmail.com
 * @date 2012-6-11
 * @since 1.0
 */
public class ApplicationContextFactory {
	
	private static final Log log = LogFactory.getLog(ApplicationContextFactory.class);
	
	private static ApplicationContext ctx = null;
	
	private static final String PROPERTIES_FILES = "com/jqd/framework/core/spring/context.properties";
	
	private static final String CONFIG_LOCATION_KEY = "config.location";
	
	
	public static ApplicationContext getCurrentApplicationContext() {
		if (ctx == null) {
			try {
				// 某些场景下ctx==null（如运行junit测试时）；需要手工加载配置文件的方式来获取spring容器
				Properties p = PropertiesUtils.loadProperties(PROPERTIES_FILES);
				ctx = new ClassPathXmlApplicationContext(p.getProperty(CONFIG_LOCATION_KEY));
			}
			catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return ctx;
	}
	
	
	public static ApplicationContext getApplicationContext(String... configLocations) {
		// 如果没有指定配置文件,则返回当前应用中的 ApplicationContext
		if (configLocations == null || configLocations.length == 0) {
			return getCurrentApplicationContext();
		}
		
		return new ClassPathXmlApplicationContext(configLocations);
	}
	
	
	public static void setApplicationContext(ApplicationContext applicationContext) {
		ctx = applicationContext;
		
		if (log.isInfoEnabled()) {
			log.info("setApplicationContext : " + applicationContext.toString());
		}
	}
	
}
